package com.lyq.blog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyq.blog.model.Result;
import com.lyq.blog.model.UserInfo;
import com.lyq.blog.service.UserService;
import com.lyq.blog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Component
public class LoginHandler implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("user_token");
        log.info("拦截器 token:{}", token);
        if (!StringUtils.hasLength(token)) {
            setResponse(response);
            return false;
        }
        Claims claims = null;
        claims = JwtUtil.parserToken(token);
        if (claims == null) {
            //token过期或解析失败
            setResponse(response);
            return false;
        }
        //检验用户是否存在
        UserInfo userInfo = userService.getUserInfoById((Integer) claims.get("id"));
        if (null != userInfo) {
            return true;
        }
        log.warn("LoginHandler 用户不存在");
        setResponse(response);
        return false;
    }

    @SneakyThrows
    public void setResponse(HttpServletResponse response) {
        ObjectMapper objectMapper = new ObjectMapper();
        String ret = objectMapper.writeValueAsString(Result.loginOut());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(ret);
        writer.flush();
    }
}
